package com.wyp168.socket.QQ.qqserver.services;

import com.wyp168.socket.QQ.qqclient.common.Message;
import com.wyp168.socket.QQ.qqclient.common.constant.MessageType;
import com.wyp168.socket.QQ.qqclient.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.List;


/**
 * 服务端推送新闻的线程
 */
public class ServerPushMessageThread extends Thread{


    @Override
    public void run() {
        while (true) {
            ObjectOutputStream oos = null;
            try {
                System.out.print("请输入服务器请求推送的消息内容: ");
                String content = Utility.scanner.nextLine();
                if (!content.equals("") && content != null) {
                    //构建message 对象
                    Message message = new Message();
                    message.setMessageType(MessageType.SERVER_PUSH_MESSAGE);
                    message.setContent(content);
                    message.setSender("server 001");
                    message.setSentTime(new Date().toString());

                    //获取服务端管理socket集合的所有userId
                    List<String> userIds = ManagerClientSocketThread.getAllExcludeBySenderId("");
                    //通过userId获取socket，并将内容以流的形式写入到数据通道
                    for (String userId : userIds) {
                        oos = new ObjectOutputStream(ManagerClientSocketThread.getServerConnectClientThread(userId).getSocket().getOutputStream());
                        oos.writeObject(message);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}
